<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\index\service;

use app\index\model\MsgTemplate;
use app\index\model\WechatTemplate;
use app\index\model\WxaMessage;
use app\sadmin\model\Lessee;
use think\Exception;
use think\facade\Config;
use WeChat\Script;
use think\facade\Db;


/**
 * 微信公众号工具
 * @package app\madmin\service
 */
class WxToolService
{

    private $configuration;

    private $user;

    public function __construct()
    {
        $configurationService = new ConfigurationService();

        list($code, $this->configuration) = $configurationService->read("wx");
        if ($code != HTTP_SUCCESS) {
            throw new Exception("请先完成配置", HTTP_NOTACCEPT);
        }
        if (
            empty($this->configuration) ||
            empty($this->configuration['appid']) ||
            empty($this->configuration['appsecret'])
        ) {
            throw new Exception("请先完善公众号配置", HTTP_NOTACCEPT);
        }

        global $user;
        $this->user = $user;

    }


    public function sign($frontUrl)
    {
        $script = new Script($this->configuration);
        $jsSign = $script->getJsSign($frontUrl);
        return [HTTP_SUCCESS, $jsSign];
    }

    public function subscribeMessage($type)
    {
        $baseTemplateId = Config::load('extension/baseTemplateId', 'baseTemplateId');
        $tmplIds = [];
        switch ($type) {
            case "pay":
                $msg = MsgTemplate::where([
                    'type' => "订单支付通知",
                    'status' => 1,
                    'channel' => 2
                ])->find();
                if (!empty($msg)) {
                    $temp = WechatTemplate::find($msg['template_id']);
                    $tmplIds[] = $temp['template_id'];
                }
                $msg2 = MsgTemplate::where([
                    'type' => "订单发货通知",
                    'status' => 1,
                    'channel' => 2
                ])->find();
                if (!empty($msg2)) {
                    $temp = WechatTemplate::find($msg2['template_id']);
                    $tmplIds[] = $temp['template_id'];
                }
                break;
            case "withdraw":
                $msg = MsgTemplate::where([
                    'type' => "提现成功通知",
                    'status' => 1,
                    'channel' => 2
                ])->find();
                if (!empty($msg)) {
                    $temp = WechatTemplate::find($msg['template_id']);
                    $tmplIds[] = $temp['template_id'];
                }
                break;
            case "recharge":
                $msg = MsgTemplate::where([
                    'type' => "充值成功通知",
                    'status' => 1,
                    'channel' => 2
                ])->find();
                if (!empty($msg)) {
                    $temp = WechatTemplate::find($msg['template_id']);
                    $tmplIds[] = $temp['template_id'];
                }
//                $tmplIds[] = $baseTemplateId['充值成功通知'][2];
                break;
        }
        return [HTTP_SUCCESS, $tmplIds];
    }

    public function getSubcribeMessageResult(array $data)
    {
        foreach ($data as $k => $v) {
            if ($v !== "accept")
                continue;
            $model = WxaMessage::where(['user_id' => $this->user['id'], 'template_id' => $k])->find();
            if (empty($model)) {
                $data = [
                    "user_id" => $this->user['id'],
                    'template_id' => $k
                ];
                WxaMessage::create($data);
            } else {
                $model->inc("count", 1)->update();
            }
        }
        return [HTTP_SUCCESS, "添加成功"];
    }

    /**
     * 微信端是否开启
     * @return array
     * @throws
     */
    public function check()
    {
        $mid = request()->header("mid");
        $les = json_decode(Db::name('lessee')->find($mid)['entry_type']);
        if (in_array(2, $les) && isset($this->configuration['is_open']) && $this->configuration['is_open'] == 1) {
            return [HTTP_SUCCESS, true];
        }
        return [HTTP_SUCCESS, false];
    }
}
